package cvs;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class CSVGenerator {

	File file;
	BufferedWriter out;

	public static char comma = ',';
	public static char quotation = '"';

	public static char r = '\r';
	public static char n = '\n';
	public static String line_separator = System.getProperty("line.separator");

	public CSVGenerator(File file) {

		this.file = file;
		try {
			out = new BufferedWriter(new FileWriter(file), 4096);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String fileToString(String file) {

		FileReader fileReader;
		StringBuffer sql = new StringBuffer();
		try {
			fileReader = new FileReader(file);
			BufferedReader reader = new BufferedReader(fileReader);

			String line = null;
			while ((line = reader.readLine()) != null) {
				sql.append(line);
				sql.append("\n");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return sql.toString();
	}

	public CSVGenerator(File file, String[] columns) {
		this(file);

		try {
			boolean is_first = true;
			for (String string : columns) {
				String value = changeToCSV(string);

				if (is_first)
					out.write(value);
				else
					out.write("," + value);
				is_first = false;
			}
			out.write(line_separator);
		} catch (Exception e) {
		}
	}

	public void build(ResultSet rs) throws SQLException, IOException {

		ResultSetMetaData rsmd = rs.getMetaData();
		int columns = rsmd.getColumnCount();

		// print header
		boolean is_first = true;
		for (int i = 1; i <= columns; i++) {
			String value = changeToCSV(rsmd.getColumnLabel(i));

			if (is_first)
				out.write(value);
			else
				out.write("," + value);
			is_first = false;
		}
		out.write("\n");

		while (rs.next()) {
			try {

				is_first = true;

				for (int i = 1; i <= columns; i++) {
					String value = changeToCSV(rs.getString(i));

					if (is_first)
						out.write(value);
					else
						out.write("," + value);
					is_first = false;
				}
				out.write("\r\n");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public String changeToCSV(String cell) {
		if (cell == null) {
			return "";
		}

		cell = cell.replace(CSVGenerator.r, ' ');
		cell = cell.replace(CSVGenerator.n, ' ');

		if (cell.indexOf(CSVGenerator.comma) >= 0
				|| cell.indexOf(CSVGenerator.quotation) >= 0) {
			String newCell = cell.replaceAll("\"", "\"\"");
			return "\"" + newCell + "\"";
		} else
			return cell;

	}

	public void close() {
		try {
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
